﻿"""
    Document   : plugin.py
    Package    : Jamendo Radio
    Author     : Ángel Fernández Pineda
    Copyright  : 2011, Ángel Fernández Pineda, Spain
    License    : Gnu General Public License - see LICENSE.TXT
    Description: plugin implementation
"""
"""
    This file is part of "Jamendo Radio plugin for XBMC"

    The "Jamendo Radio plugin for XBMC" is free software: you can redistribute
    it and/or modify it under the terms of the GNU General Public License as
    published by the Free Software Foundation, either version 3 of the License,
    or (at your option) any later version.

    The "Jamendo Radio plugin for XBMC" is distributed in the hope that it will
    be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with the "Jamendo Radio plugin for XBMC".
    If not, see <http://www.gnu.org/licenses/>.
"""

import xbmc
import xbmcgui
import xbmcplugin
import jamendo_radio_rpc

# String identifiers, as defined in strings.xml
_STR_POPULATING = 30200
_STR_PLAY = 208 # 30300
_STR_ENQUEUE = 526 # 30310

# Plugin implementation

def enumerate_radio_stations(instance):
    radios = jamendo_radio_rpc.get_radio_stations()
    for radio in radios:
        litem = xbmcgui.ListItem(radio["name"])
        litem.setIconImage(radio["image"])
        xbmcplugin.addDirectoryItem(instance.id,
                                    instance.url({
                                        "state":    "radioselected",
                                        "station":  radio["id"]
                                    }),
                                    litem,
                                    True,
                                    len(radios))
    #end for
    xbmcplugin.endOfDirectory(instance.id)
#end def

def ask_for_action(instance):
    # Set two list items, one for "play" and one for "enqueue"
    litem = xbmcgui.ListItem(instance.string(_STR_PLAY))
    xbmcplugin.addDirectoryItem(instance.id,
                                instance.url({
                                    "state":    "actionselected",
                                    "station":  instance.data["station"],
                                    "action":   "play"
                                }),
                                litem,
                                True,
                                2)
    litem = xbmcgui.ListItem(instance.string(_STR_ENQUEUE))
    xbmcplugin.addDirectoryItem(instance.id,
                                instance.url({
                                    "state":    "actionselected",
                                    "station":  instance.data["station"],
                                    "action":   "enqueue"
                                }),
                                litem,
                                True,
                                2)
    xbmcplugin.endOfDirectory(instance.id)
#end def

def play_or_enqueue(instance):
    radio_id_str = instance.data["station"]
    # Read user settings
    max_item_count = int(instance.setting("playlist_size"))
    if (max_item_count<1):
        # should not happen, but who knows...
        max_item_count = 150
    elif (max_item_count>1500):
        # should not happen, but who knows...
        max_item_count = 150
    #end if

    ## Initialize some variables, create a progress bar
    ## and create a playlist
    listener_id_str = jamendo_radio_rpc.get_listener_id()
    progress_dlg = xbmcgui.DialogProgress()
    progress_dlg.create(instance.string(_STR_POPULATING))
    progress_dlg.update(1) # show progress bar
    playlist = xbmc.PlayList(xbmc.PLAYLIST_MUSIC)
    if (instance.data["action"]=="play"):
        playlist.clear()
    count = 0
    more = True

    ## repeat until no more streams available, user cancelation,
    ## or user-configured stream count is reached at playlist
    while more:
        # get some streams from jamendo
        partial = jamendo_radio_rpc.get_playlist(
            radio_id_str,
            listener_id_str,
            count)
        count = count + len(partial)
        progress_dlg.update(count*100//max_item_count)
        more = ((len(partial)>0) and
                (count<max_item_count) and
                (not progress_dlg.iscanceled()))
        # add streams to playlist
        for stream in partial:
            litem = xbmcgui.ListItem(stream["name"])
            litem.setIconImage(stream["album_image"])
            litem.setThumbnailImage(stream["album_image"])
            litem.setPath(stream["stream"])
            litem.setInfo("music",
            {
                "album": stream["album_name"],
                "duration": int(stream["duration"])
            })
            playlist.add(stream["stream"],litem)
        #end for
    #end while
                
    # start playing
    player = xbmc.Player(xbmc.PLAYER_CORE_MPLAYER)
    if (instance.data["action"]=="play") or (not player.isPlaying()):
        player.play(playlist)
    progress_dlg.close()
#end def
        
def start(instance):
    print("------ START OF JAMENDO RADIO PLUGIN -----")
    if (instance.data==None): 
        enumerate_radio_stations(instance) 
    elif (instance.data["state"]=="radioselected"):
        ## User has selected a radio station, ask what to do next
        ask_for_action(instance)
    elif (instance.data["state"]=="actionselected"):
        ## User has selected an action on a radio station (play/enqueue)
        play_or_enqueue(instance)
        xbmc.executebuiltin('Action(ParentDir)')
    else:
        # should not happen
        raise Exception 
    print("------ END OF JAMENDO RADIO PLUGIN -----")
#end def
